package cn.jlearn.proxy.web.service.impl;

import cn.dev33.satoken.secure.SaSecureUtil;
import cn.dev33.satoken.stp.StpUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.lang.UUID;
import cn.hutool.core.util.RandomUtil;
import cn.jlearn.proxy.web.enums.MemberStatusEnum;
import cn.jlearn.proxy.web.mapper.MemberMapper;
import cn.jlearn.proxy.web.model.Member;
import cn.jlearn.proxy.web.pojo.R;
import cn.jlearn.proxy.web.service.MemberService;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.List;

/**
 * @author qianyingchao
 * @version 1.0
 * @date 2021/7/15 2:14 下午
 */
@Service
public class MemberServiceImpl implements MemberService {

    @Resource
    private MemberMapper memberMapper;

    @Override
    public R<Member> login(String email, String password, Boolean remember) {
        LambdaQueryWrapper<Member> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Member::getEmail, email);
        List<Member> members = memberMapper.selectList(queryWrapper);
        if (CollUtil.isEmpty(members)) {
            return R.fail("416", "邮箱或密码错误");
        }
        Member member = members.get(0);
        password = SaSecureUtil.md5BySalt(password, member.getSalt());
        if (!password.equals(member.getPassword())) {
            return R.fail("416", "邮箱或密码错误");
        }
        if (!MemberStatusEnum.NORMAL.getCode().equals(member.getStatus())) {
            return R.fail("416", "账号状态非正常");
        }
        StpUtil.login(member.getId(), remember);
        StpUtil.getSession().set("uid", member.getUid());
        return R.success(member);
    }

    @Override
    public R<Member> register(String email, String password) {
        LambdaQueryWrapper<Member> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(Member::getEmail, email);
        List<Member> members = memberMapper.selectList(queryWrapper);
        if (CollUtil.isNotEmpty(members)) {
            return R.fail("416", "该邮箱已经被注册");
        }
        Member member = new Member();
        member.setUid(UUID.randomUUID(true).toString(true));
        member.setEmail(email);
        String salt = RandomUtil.randomString(32);
        member.setSalt(salt);
        member.setPassword(SaSecureUtil.md5BySalt(password, salt));
        member.setStatus(MemberStatusEnum.NORMAL.code);
        memberMapper.insert(member);
        return R.success(member);
    }

}
